<!DOCTYPE html> 
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>放大镜</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }

        body {
            background: #ad2b2b; 
        }

        #small {
            width: 578px; 
            height: 324px;
            position: absolute; 
            left: 10px;
            top: 50px;
        }

        #box {
            width: 172px; 
            height: 97px;
            background-color: #8783D6; 
            cursor: crosshair; 
            position: absolute; 
            top: 0px; 
            left: 0px; 
            opacity: 0;
        }

        #big {
            width: 576px; 
            height: 324px;
            overflow: hidden; 
            position: absolute; 
            left: 628px; 
            top: 50px; 
            display: none;
        }

    </style>
</head>
<body>
    <!-- 小图 --> 
    <div id="small">
        <img src="./image/smallimage.jpg" /> 
        <div id="box"></div>
    </div>

    <!-- 大图 -->
    <div id="big">
        <img src="./image/bigimage .jpg" id="img" style="position:absolute; left:0; top:0;" />
    </div>
</body>
</html>

    <script>
        // 通过ID的形式获取元素
        var small = document.getElementById('small')
        var box = document.getElementById('box')
        var big = document.getElementById('big')
        var img = document.getElementById('img')

        // 给小图绑定鼠标移动事件 e = event 事件事件
        small.onmousemove = function(e) 
        {
            // 让盒子和大图显示
            box.style.opacity = 0.5
            big.style.display = 'inline-block'

            // 得到移动的坐标
            // console.log(e.clientX, e.clientY);

            // 获取元素的外边距
            // console.log(small.offsetLeft, small.offsetTop);

            // 盒子的一半 172 / 2 97 / 2
            var x = e.clientX - small.offsetLeft - 86
            var y = e.clientY - small.offsetTop - 48.5

            if (x < 0) { // 超出左边
                x = 0;
            } else if (x > 404)  // 右边 小图宽 - 盒子宽 576-172
            {
                x = 404;
            }

            if (y < 0)  // 超出 上面
            {
                y = 0;
            } else if (y > 227)  // 324- 97
            {
                y = 227;
            }

            // 设置box盒子的位置坐标 
            box.style.left = `${x}px`;
            box.style.top = `${y}px`;

            // 大图和小图的比率关系计算 小图移动1px 然后在大图上移动多少3.33333px
            //大图1920/小图576 宽度
            //大图1080/小图324 高度
            img.style.left = `-${x * (1920 / 576)}px`;
            img.style.top = `-${y * (1080 / 324)}px`;
        }

        // 移出事件
        small.onmouseleave = function() 
        {
            // 让盒子和大图隐藏 
            box.style.opacity = 0
            big.style.display = 'none'
        }
    </script>
